<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".($_GET["type"]=="add"? __("Add Member") : __("Update Member"));
$page_title=$_GET["type"]=="add"? __("Add Member") : __("Update Member");
$list_file=$vars["file"]["admin"]["member_list"];

if(!$pv["task"]["Members"]){
 $errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage Member."));

 print format_admin_page($errmsg, $this_title);
 exit();
}

if(!in_array($_GET["type"], array("add","edit"))){
 header("location: $this_file?type=add");
 exit();
}

if($_GET["type"]=="edit"){
 if(!$get_s["id"]){
  $errmsg=__("No member with that ID found!");
 }elseif(!@mysql_num_rows($r=mysql_query("select * from $db->users where id='$get_d[id]'"))){
  $errmsg=__("No member with that ID found!");
 }else{
  $r_user=mysql_fetch_assoc($r);
 }
}

if($errmsg){
 $errmsg="<h2>$page_title</h2>".format_err($errmsg);

 print format_admin_page($errmsg, $this_title);
 exit();
}

$r_position=array(1,2);
$r_position_d=array(1=>'Left',2=>'Right');
$r_rank_index = array("0.0","5.0","10.0","100.0","300.0");
$r_rank_index_d = $vars['rank_index_a_d'];
$r_rank_index_d[0] = __("None");
$r_status=array("normal","suspended","terminated");
$r_status_d=array("normal"=>__("Normal"),"suspended"=>__("Suspended"),"terminated"=>__("Terminated"));
$r_gender=array("m","f");
$r_gender_d=array("m"=>__("Male"),"f"=>__("Female"));
$r_activated=array("y","n");
$r_activated_d=array("y"=>__("Yes"),"n"=>__("No"));
$r_is_stockist=array("y","n");
$r_is_stockist_d=array("y"=>__("Yes"),"n"=>__("No"));$r_site_visit=array("y","n");$r_site_visit_d=array("y"=>__("Yes"),"n"=>__("No"));
$country_code=$vars['common']['country_code'];
array_shift($country_code);
$country_code_t=$vars['common']['country_code_text'];
foreach($country_code_t as $code=>$cname){
 $country_code_d[$code]=__($cname);
}

$td_width=180;
$datetime=ndate($vars["system_date_format"]);
$settings=get_settings('activation_fee');

//#####AJAX CALL#####
if($_GET["aj"] && ($_GET["check_ref"] || $_GET["check_upline"])){
 if(!$r_ref=get_user_detail_by_id($post_d['ref'])){
  $ajerrmsg=replace_tag(__("Member ID '<%id%>' could not be found."), array("<%id%>"=>$post_h['ref']));
 }elseif(0){//$r_ref['activated']!='y'){
  $ajerrmsg=replace_tag(__("Member ID '<%id%>' is not activated."), array("<%id%>"=>$post_h['ref']));
 }else{
  $ajmsg=replace_tag(__("Member ID: <%id%>, Name: <%name%>"), array("<%id%>"=>$post_h['ref'], "<%name%>"=>$r_ref['name']));
 }
 $xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);
 print format_xml($xml);
 exit();
}
//#####END AJAX CALL#####

//#####ADD / EDIT MEMBER POST#####
if($_POST["__req"]){
 //#####ERROR CHECK#####
 $chk_arr="_ref,_name,_username,_email,_address,_address2,_city,_zip,_state,_mobileno,_officeno,_faxno,_bank_name,_bank_acc_no,_bank_swiftcode,_bank_branch,_payee_name,_remark";
 if($post_s["acc_type"]=="p"){
  $chk_arr.=",_ic,_homeno,_occupation";
 }else{
  $chk_arr.=",_bis_reg,_person_in_charge";
 }
 if($_GET["type"]=="add" || $_GET["type"]=="edit" && strlen($post_s["_password"])){
  $chk_arr.=",_password";
 }
 $chk_arrr=explode(",", $chk_arr);
 foreach($post_s as $f=>$v){
  if(in_array($f, $chk_arrr)){
   $data[$f]=$v;
  }
 }
 $errmsg=verify_form_data("users", $data);
 if(!$errmsg){
  //check referrer
  if(strlen($post_s['_ref']) && $post_s['_ref']!=0){
   if(!$r_ref=get_user_detail_by_id($post_d["_ref"])){
    $errmsg.=replace_tag(__("Sponsor ID: '<%id%>' cannot be found in the database."), array("<%id%>"=>$post_h['_ref']))."<br />\n";
   }elseif($r_ref['status']=='terminated'){
    $errmsg.=replace_tag(__("Sponsor ID: '<%id%>' is terminated."), array("<%id%>"=>$post_h['_ref']))."<br />\n";
   }elseif(0){//$r_ref['activated']!='y'){
    $errmsg.=replace_tag(__("Sponsor ID: '<%id%>' is not activated."), array("<%id%>"=>$post_h['_ref']))."<br />\n";
   }
  }
		//check placement
		if($get_s['type']=='add'){
			if($post_s["matrix_upline"]){
				if(!$r_upline=@mysql_fetch_assoc(mysql_query("select * from $db->users where id='$post_d[matrix_upline]' and status in ('suspended','normal')"))){
					$errmsg.=replace_tag(__("Placement ID: '<%rid%>' cannot be found in the database."), array("<%rid%>"=>$post_h['matrix_upline']))."<br />\n";
				}else{
					if(!in_array($post_s['matrix_position'], $r_position)){
						$errmsg.=__("Please select a placement position.")."<br />";
					}elseif(@mysql_num_rows(mysql_query("select * from $db->users where matrix_upline='$post_d[matrix_upline]' and matrix_position='$post_d[matrix_position]'"))){
						$errmsg.=__("The selected Placement ID and Placement Position is already occupied.")."<br />";
					}
				}
			}else{
				$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Placement ID")))."<br />";
			}
			if(!$errmsg){
				if($post_s['matrix_upline'] != $post_s['_ref'] && !is_group_matrix_downline_of($post_s['matrix_upline'], $post_s['_ref'])){
					$errmsg.=__("The selected Placement ID is not in the network group of the Sponsor ID.")."<br />";
				}
			}
		}
  if($post_s["acc_type"]=="p"){
   //check ic
//   if($_GET["type"]=="edit" && $post_s["_ic"]!=$r_user["ic"] && ic_found($post_d["_ic"])) {
//    $errmsg.=replace_tag(__("I/C No. '<%ic%>' belongs to another member."), array("<%ic%>"=>$post_h['_ic']))."<br />\n";
//   }elseif($_GET["type"]=="add" && ic_found($post_d["_ic"])){
//    $errmsg.=replace_tag(__("I/C No. '<%ic%>' belongs to another member."), array("<%ic%>"=>$post_h['_ic']))."<br />\n";
//   }
   //check dob
   if(strlen($post_s["dob_day"]) || strlen($post_s["dob_month"]) || strlen($post_s["dob_year"])){
    $dob="$post_s[dob_year]-".pad_length($post_s["dob_month"], 2)."-".pad_length($post_s["dob_day"], 2);
    if(!@checkdate($post_s["dob_month"], $post_s["dob_day"], $post_s["dob_year"])){
     $errmsg.=__("Invalid date format selected for DOB.")."<br />\n";
    }
   }
   //check gender
   if(!in_array($post_s["gender"], $r_gender)){
    $errmsg.=__("Please specify Gender.")."<br />\n";
   }
  }elseif($post_s["acc_type"]=="c"){
   //check business reg no
   if($_GET["type"]=="edit" && $post_s["_bis_reg"]!=$r_user["bis_reg"] && bis_reg_found($post_d["_bis_reg"])) {
    $errmsg.=replace_tag(__("Company Reg. No. '<%reg%>' belongs to another member."), array("<%reg%>"=>$post_h['_bis_reg']))."<br />\n";
   }elseif($_GET["type"]=="add" && bis_reg_found($post_d["_bis_reg"])){
    $errmsg.=replace_tag(__("Company Reg. No. '<%reg%>' belongs to another member."), array("<%reg%>"=>$post_h['_bis_reg']))."<br />\n";
   }
  }
  //check username
  if($_GET["type"]=="edit" && $post_s["_username"]!=$r_user["username"] && username_found($post_d["_username"])){
   $errmsg.=replace_tag(__("The username '<%username%>' is already in use. Please provide another."), array("<%username%>"=>$post_h['_username']))."<br />\n";
  }elseif($_GET["type"]=="add" && username_found($post_d["_username"])){
   $errmsg.=replace_tag(__("The username '<%username%>' is already in use. Please provide another."), array("<%username%>"=>$post_h['_username']))."<br />\n";
  }
  //account misc
  if(!in_array($post_s["is_stockist"], $r_is_stockist)){
   $errmsg.=__("Please specify Stockist.")."<br />\n";
  }
  if(!in_array($post_s["rank_a"], $r_rank_index)){
   $errmsg.=__("Please specify member rank.")."<br />\n";
  }
  if($_GET["type"]=="edit" && !in_array($post_s["status"], $r_status)){
   $errmsg.=__("Please specify Member Status.")."<br />\n";
  }
  if(strlen($post_s["cdate"])){
   if(!verify_date($post_s["cdate"])){
    $errmsg.=__("Invalid Join Date format.")."<br />\n";
   }
  }
 }
 //#####END ERROR CHECK#####

 //#####ADD TO DB#####
 if(!$errmsg){
  if($_GET["type"]=="add"){//add
   //field formatting
   $field_arr=explode(",", $chk_arr);
   for($i=0,$t=count($field_arr);$i<$t;$i++){
    $ufq.=($ufq? ", " : "").(substr($field_arr[$i], 0, 1) == '_'? substr($field_arr[$i], 1) : $field_arr[$i]);
    $uvq.=($uvq? ", " : "")."'".$post_d[$field_arr[$i]]."'";
   }
   if($post_s["acc_type"]=="p"){
    $ufq.=", dob, gender";
    $uvq.=", '$dob', '$post_d[gender]'";
   }
   $salt=generate_random_code(32);
   $enc_pass=md5($post_s["_password"].$salt).":".$salt;
   $new_status="normal";
   $join_date=$post_s["cdate"]? $post_s["cdate"] : $datetime;      switch($post_d['rank_a']){   		case 1.0:	        $owallet = 1000;	        break;        case 3.0:	        $owallet = 3000;	        break;	    case 7.0:	        $owallet = 7000;	        break;	    case 15.0:	        $owallet = 15000;	        break;	    case 30.0:	        $owallet = 30000;	        break;	    case 90.0:	        $owallet = 90000;	        break;	    default:	    	$owallet = 0;	    	break;   }   
   $sql="insert into $db->users (acc_type, is_stockist, site_visit, rank_a, matrix_upline, matrix_position, $ufq, enc_password, ewallet_enc_password, epoint_enc_password, country, activated, activated_date, status, cdate, owallet)
   values ('$post_d[acc_type]', '$post_d[is_stockist]', '$post_d[site_visit]', '$post_d[rank_a]', '$post_d[matrix_upline]', '$post_d[matrix_position]', $uvq, '$enc_pass', '$enc_pass', '$enc_pass', '$post_d[country]', '".($post_s['rank_a']>0? 'y' : 'n')."', '".($post_s['rank_a']>0? $datetime : "")."', '$new_status', '$join_date', '$owallet')";
   if(!mysql_query($sql)){
    $errmsg.=__("Error creating a new member.")."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
   }else{
    $new_uid=mysql_insert_id();        mysql_query("update $db->users set code=username where code='' or code is null");
    //email user
    if($post_s["email_user"]){
     $msg_style=$vars['css']['msg_style'];
     $td_style=$vars['css']['td_style'];
     $td_title_style=$vars['css']['td_title_style'];
     $u_sub="$vars[title] - New Account for $post_s[_email]";
     $u_msg="
     <p $msg_style>Dear $post_s[_name], <br />\n<br />\nThe administrative staff of $vars[title] has created a new account for you using ".
     "your email '$post_s[_email]'. You can now login to your account at <a href='".M_URL."'>".M_URL."</a>. The user information for your new account is listed below:</p>
     <table align='center' ".$vars['css']['table_style']." width='100%'>
      <tr>
       <td $td_title_style colspan='2'>Account Information</td>
      </tr>
      <tr>
       <td $td_style width='120'>Account ID</td>
       <td $td_style>$new_uid</td>
      </tr>
      <tr>
       <td $td_style>Referrer</td>
       <td $td_style>".($post_s['_ref']? "ID: $post_s[_ref] ($r_ref[name])" : "None")."</td>
      </tr>
      <tr>
       <td $td_style>Username</td>
       <td $td_style>$post_s[_username]</td>
      </tr>
      <tr>
       <td $td_style>Password</td>
       <td $td_style>$post_s[_password]</td>
      </tr>
      <tr>
       <td $td_title_style colspan='2'>User Information</td>
      </tr>
      <tr>
       <td $td_style width='120'>".($post_s["acc_type"]=="c"? "Company " : "")."Name</td>
       <td $td_style>$post_s[_name]</td>
      </tr>
      <tr>
       <td $td_style>".($post_s["acc_type"]=="c"? "Company Reg. No." : "IC No.")."</td>
       <td $td_style>".($post_s["acc_type"]=="c"? $post_s["_bis_reg"] : $post_s["_ic"])."</td>
      </tr>".($post_s["acc_type"]=="p"? "
      <tr>
       <td $td_style>Gender</td>
       <td $td_style>".$r_gender_d[$post_s["gender"]]."</td>
      </tr>" : "")."
      <tr>
       <td $td_style>Country</td>
       <td $td_style>".$country_code_d[$post_s["country"]]."</td>
      </tr>
      <tr>
       <td $td_style>Mobile No.</td>
       <td $td_style>$post_s[_mobileno]</td>
      </tr>".($post_s["acc_type"]=="c"? "
      <tr>
       <td $td_style>Telephone No.</td>
       <td $td_style>$post_s[_officeno]</td>
      </tr>
      <tr>
       <td $td_style>Fax No.</td>
       <td $td_style>$post_s[_faxno]</td>
      </tr>" : "")."
      <tr>
       <td $td_style>Email</td>
       <td $td_style>$post_s[_email]</td>
      </tr>
     </table>";
     if(email_user($post_s["_email"], $u_sub, $u_msg)){
      $email_msg=replace_tag(__("A welcome email has been sent to '<%email%>'."), array("<%email%>"=>$post_h['_email']));
     }else{
      $email_msg=replace_tag(__("Welcom email could not be sent to '<%email%>'."), array("<%email%>"=>$post_h['_email']));
     }
    }
   }
   if(!$errmsg){
    $msg=__("The new member has been successfully created.").($email_msg? " $email_msg" : "")."<br />\n";
   }
  }else{//update
   //field formatting
   $field_arr=explode(",", $chk_arr);
   for($i=0,$t=count($field_arr);$i<$t;$i++){
    $uq.=($uq? ", " : "").(substr($field_arr[$i], 0, 1) == '_'? substr($field_arr[$i], 1) : $field_arr[$i])."='".$post_d[$field_arr[$i]]."'";
   }
   if($post_s["acc_type"]=="p"){
    $uq.=", dob='$dob', gender='$post_d[gender]'";
   }
   if(strlen($post_s["_password"])){
    $salt=generate_random_code(32);
    $enc_pass=md5($post_s["_password"].$salt).":".$salt;
    $password_q="enc_password='$enc_pass',";
   }
   $sql="update $db->users set acc_type='$post_d[acc_type]', is_stockist='$post_d[is_stockist]', site_visit='$post_d[site_visit]', rank_a='$post_d[rank_a]', ".($post_s['rank_a']>0? "activated='y', ".($r_user['activated_date']=='0000-00-00 00:00:00'? "activated_date='$datetime', " : "") : ($r_user['activated_date']=='0000-00-00 00:00:00'? "activated='n', " : ""))."$uq, $password_q country='$post_d[country]', status='$post_d[status]' ".($post_s["cdate"]? ", cdate='$post_d[cdate]' " : "")." where id='$get_d[id]' limit 1";
   if(!mysql_query($sql)){
    $errmsg.=__("Error updating the member record.")."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
   }
   if(!$errmsg){
    $msg=__("The member record has been successfully updated.")."<br />\n";
    $r_user=mysql_fetch_assoc(mysql_query("select * from $db->users where id='$get_d[id]'"));
   }
  }
 }

 $msg=$msg? format_msg($msg) : "";
 $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}
//#####END MEMBER POST#####

$form_fields=array("acc_type"=>"p","_ref"=>"","matrix_upline"=>"","matrix_position"=>"","_ic"=>"","_bis_reg"=>"","_person_in_charge"=>"","_name"=>"","_username"=>"","_password"=>"","_email"=>"","_address"=>"","_address2"=>"","_city"=>"","_zip"=>"","_state"=>"","country"=>"MY","_homeno"=>"","_mobileno"=>"","_officeno"=>"","_faxno"=>"","dob_day"=>"","dob_month"=>"","dob_year"=>"","gender"=>"m","_bank_name"=>"","_bank_acc_no"=>"","_bank_swiftcode"=>"","_bank_branch"=>"","_payee_name"=>"","_occupation"=>"","is_stockist"=>"n","site_visit"=>"n","rank_a"=>"0","status"=>"normal","cdate"=>"","_remark"=>"");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=(!$post_s["__req"]? ($_GET["type"]=="edit"? nhtmlentities($r_user[$db_fieldname]) : $default) : $post_h[$field]);
}
$dis["_password"]=$_GET["type"]=="edit" && !$post_s["__req"]? "" : $dis["_password"];
$dis["dob_day"]=(!$post_s["__req"]? ($_GET["type"]=="edit"? ($r_user["dob"]=="0000-00-00"? "" : date("j", strtotime($r_user["dob"]))) : "") : $post_s["dob_day"]);
$dis["dob_month"]=(!$post_s["__req"]? ($_GET["type"]=="edit"? ($r_user["dob"]=="0000-00-00"? "" : date("n", strtotime($r_user["dob"]))) : "") : $post_s["dob_month"]);
$dis["dob_year"]=(!$post_s["__req"]? ($_GET["type"]=="edit"? ($r_user["dob"]=="0000-00-00"? "" : date("Y", strtotime($r_user["dob"]))) : "") : $post_s["dob_year"]);
$dis["cdate"]=(!$post_s["__req"]? ($_GET["type"]=="edit"? ($r_user["cdate"]=="0000-00-00 00:00:00"? "" : $r_user["cdate"]) : "") : $post_h["cdate"]);
$email_user=(!$post_s["__req"]? 1 : $post_s["email_user"]);

$position_select=build_select($r_position, $r_position_d, $dis['matrix_position'], 'matrix_position', $inputbox_style);
$country_select=build_select($country_code, $country_code_d, $dis["country"], "country", $inputbox_style);
$is_stockist_select=build_select($r_is_stockist, $r_is_stockist_d, $dis["is_stockist"], "is_stockist", $inputbox_style);
$rank_select=build_select($r_rank_index, $r_rank_index_d, $dis["rank_a"], "rank_a", $inputbox_style);
$status_select=build_select(($_GET["type"]=="add"? $r_status_new : $r_status), $r_status_d, $dis["status"], "status", $inputbox_style);
$gender_select=build_select($r_gender, $r_gender_d, $dis["gender"], "gender", $inputbox_style);
$dob_input=generate_dmy_input("dob", $dis["dob_day"], $dis["dob_month"], $dis["dob_year"], "class='inputbox'");
$site_visit_select=build_select($r_site_visit, $r_site_visit_d, $dis["site_visit"], "site_visit", $inputbox_style);
//referrer
if($dis["_ref"]){
 if($r=get_user_detail_by_id($dis["_ref"])){
  $ref_text="<span class='bold'>".__("Referrer ID").__(":")." $dis[_ref], ".__("Name").__(":")." ".$r["name"]."</span>";
 }else{
  $ref_text="<span class='red'>".__("Invalid Referrer")."</span>";
 }
}

if($_GET["type"]=="edit"){
 $user_point_row="
 <tr>
  <td>".__("Member Cash").__(":")."</td>
  <td>
  $vars[ewallet_title]: ".number_format($r_user["ewallet"], 2)."<br />\n
  ".__("To change member point, go to Member Point.")."</td>
 </tr>";
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=user_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });

 j('input#check_ref_btn').click(function(){
  j('span#aid_text').html('').removeClass('red');
  if(j('input[@name=_ref]').val()==''){
   j('span#ref_text').html('".AddSlashes(__("Please provide a Referrer ID!"))."').addClass('red');
  }else{
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&check_ref=1',
    data: {'ref': j('input[@name=_ref]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('span#ref_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+' ';
      });
     }
     var status=j(data).find('status').text();
     j('span#ref_text').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_ref_btn').attr('disabled','');
    }
   });
  }
 });
 
 j('input#check_up_btn').click(function(){
  j('span#up_text').html('').removeClass('red');
  if(j('input[@name=matrix_upline]').val()==''){
   j('span#up_text').html('".AddSlashes(__("Please provide an Upline ID!"))."').addClass('red');
  }else{
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&check_upline=1',
    data: {'ref': j('input[@name=matrix_upline]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('span#up_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+' ';
      });
     }
     var status=j(data).find('status').text();
     j('span#up_text').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_up_btn').attr('disabled','');
    }
   });
  }
 });
});

function update_acc_type(type){
 if(type=='p'){
  personal_d='block';
  company_d='none';
 }else{
  personal_d='none';
  company_d='block';
 }
 q('personal').style.display=personal_d;
 q('personal_home').style.display=personal_d;
 q('company').style.display=company_d;
}
</script>";

//content jvscript
$c_jvscript=
"<script type='text/javascript'>
update_acc_type('".AddSlashes($dis["acc_type"])."');
</script>";

//back button
$url_referer=$_SERVER["HTTP_REFERER"];
if($post_s["back_url"]){
 $back_url=$post_s["back_url"];
}elseif($url_referer && !strstr($url_referer, $this_file)){
 $back_url=$url_referer;
}else{
 $back_url=$list_file;
}

//format input row
if($get_s['type']=='add'){
	$display_fields=array("_ref","matrix_upline","_ic","_bis_reg","_person_in_charge","_name","_username","_password","_email","_address","_address2","_city","_zip","_state","_homeno","_mobileno","_officeno","_faxno","_bank_name","_bank_acc_no","_bank_swiftcode","_bank_branch","_payee_name","_occupation","cdate","_remark");
}else{
	$display_fields=array("_ref","_ic","_bis_reg","_person_in_charge","_name","_username","_password","_email","_address","_address2","_city","_zip","_state","_homeno","_mobileno","_officeno","_faxno","_bank_name","_bank_acc_no","_bank_swiftcode","_bank_branch","_payee_name","_occupation","cdate","_remark");
}
foreach($form_fields as $field => $default){
 if(in_array($field, $display_fields)){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dbr=explode("#", $vars["dbr"]["users"][$db_fieldname]);
  $readonly=$textarea=false;
  if($field=='_ref'){
   $extra_display="<br />\n".__("The referrer for this member.")." <span id='ref_text'>$ref_text</span> <input type='button' name='check_ref_btn' id='check_ref_btn' value=\"".__("Check Referrer")."\" />";
  }elseif($field=='matrix_upline'){
   $extra_display="<br />\n".__("The upline for this member.")." <span id='up_text'>$up_text</span> <input type='button' name='check_up_btn' id='check_up_btn' value=\"".__("Check Upline")."\" />";
  }elseif($field=='cdate'){
   $extra_display="<br />\n".__("Date Format")." YYYY-MM-DD HH:MM:SS, ".__("leave blank to use current date and time.");
  }elseif($field=='_password'){
   if($_GET["type"]=="edit"){
    $extra_display=$_GET["type"]=="edit"? "<br />\n<span class='italic'>* ".__("Only provide a password if you want to reset the password for this member.")."</span>" : "";
   }
  }else{
   $extra_display='';
  }
  if(in_array($field, array("_remark"))){
   $textarea=true;
  }
  $readonly_str=$readonly? "readonly='readonly'" : "";
  $form_inputfield[$db_fieldname]="
  <tr>
   <td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
   <td>".($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
   <input type='text' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />")."$extra_display</td>
  </tr>";
 }
}

$manage_user=($errmsg || $msg? $errmsg.$msg : "").
"<form name='aj_form' method='post' action='$this_file'></form>
<form name='user_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='back_url' value=\"$back_url\" />
<table class='amt_table'>
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='button' value=\"".__("Back")."\" onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
   <input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Member") : __("Add Member"))."\" />
  </td>
 </tr>
 <tr class='amt_header'>
  <td colspan='2'>".__("Account Information")."</td>
 </tr>".($_GET["type"]=="edit"? "
 <tr>
  <td width='$td_width'>".__("Member ID").__(":")."</td>
  <td>$get_s[id]</td>
 </tr>
 $user_point_row" : "")."
 $form_inputfield[ref]".($get_s['type']=='add'? "
 $form_inputfield[matrix_upline]
 <tr>
  <td>".__("Placement Position").__(":")." ".__("*")."</td>
  <td>$position_select</td>
 </tr>" : "")."
 $form_inputfield[username]
 $form_inputfield[password]
 <tr>
  <td>".__("Account Type").__(":")." ".__("*")."</td>
  <td><input type='radio' name='acc_type' value=\"p\" id='accp' ".($dis["acc_type"]=="p"? "checked='checked'" : "")." onclick='update_acc_type(this.value);' onkeydown='update_acc_type(this.value);' /><label for='accp'>".__("Personal")."</label>
      <input type='radio' name='acc_type' value=\"c\" id='accc' ".($dis["acc_type"]=="c"? "checked='checked'" : "")." onclick='update_acc_type(this.value);' onkeydown='update_acc_type(this.value);' /><label for='accc'>".__("Company")."</label>
  </td>
 </tr>
 $form_inputfield[name]
 $form_inputfield[email]
</table>
<div id='personal'>
<table class='amt_table'>
 $form_inputfield[ic]
 <tr>
  <td>".__("Gender").__(":")." ".__("*")."</td>
  <td>$gender_select</td>
 </tr>
 $form_inputfield[occupation]
 <tr>
  <td>".__("Date of Birth").__(":")."</td>
  <td>$dob_input</td>
 </tr>
</table>
</div>
<div id='company'>
<table class='amt_table'>
 $form_inputfield[bis_reg]
 $form_inputfield[person_in_charge]
</table>
</div>
<table class='amt_table'>
 $form_inputfield[address]
 $form_inputfield[address2]
 $form_inputfield[city]
 $form_inputfield[zip]
 $form_inputfield[state]
 <tr>
  <td>".__("Country").__(":")." ".__("*")."</td>
  <td>$country_select</td>
 </tr>
</table>
<div id='personal_home'>
<table class='amt_table'>
 $form_inputfield[homeno]
</table>
</div>
<table class='amt_table'>
 $form_inputfield[mobileno]
 $form_inputfield[officeno]
 $form_inputfield[faxno]
 <tr class='amt_header'>
  <td colspan='2'>".__("Payment Information")."</td>
 </tr> $form_inputfield[payee_name]
 $form_inputfield[bank_name]
 $form_inputfield[bank_acc_no] $form_inputfield[bank_swiftcode] $form_inputfield[bank_branch]
 <tr class='amt_header'>
  <td colspan='2'>".__("Stockist Settings")."</td>
 </tr>
 <tr>
  <td>".__("Is Stockist").__(":")." ".__("*")."</td>
  <td>$is_stockist_select</td>
 </tr>
 <tr class='amt_header'>
  <td colspan='2'>".__("Account Settings")."</td>
 </tr> <tr>  <td>".__("Site Visit").__(":")." ".__("*")."</td>  <td>$site_visit_select</td> </tr>
 <tr>
  <td>".__("Rank").__(":")." ".__("*")."</td>
  <td>$rank_select</td>
 </tr>".($_GET["type"]=="edit"? "
 <tr>
  <td>".__("Status").__(":")." ".__("*")."</td>
  <td>$status_select</td>
 </tr>" : "").($r_user['activated']=='y'? "
 <tr>
  <td>".__("Activated Date").__(":")."</td>
  <td>".date($vars['date_format'], strtotime($r_user['activated_date']))."</td>
 </tr>" : "")."
 $form_inputfield[cdate]
 $form_inputfield[remark]".($_GET["type"]=="add"? "
 <tr>
  <td></td>
  <td><input type='checkbox' name='email_user' ".($email_user? "checked='checked'" : "")." id='eu' /><label for='eu'>".__("Send a welcome email to member.")."</label></td>
 </tr>" : "")."
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='button' value=\"".__("Back")."\" onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
   <input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Member") : __("Add Member"))."\" />
  </td>
</table>
</form>
$c_jvscript";

$content="<h2>$page_title</h2>$manage_user";

print format_admin_page($content, $this_title, $jvscript);
?>